import { ref } from 'vue'
import type { MediaView } from '@/api/children.typing'
import { useAuthHeaders, getCurrentUserId } from '@/utils/token'
import { http } from '@/utils/http'

export abstract class MediaPlayer {
  // 公共状态
  playingItem = ref<MediaView | null>(null)
  isPlaying = ref(false)
  currentTime = ref(0)
  duration = ref(0)

  // 保存进度的时间间隔
  protected SAVE_INTERVAL = 10000
  protected lastSaveTime = 0

  // API基础URL
  protected API_BASE_URL = import.meta.env.VITE_API_BASE_URL

  // 抽象方法 - 必须由子类实现
  abstract play(item: MediaView, progressSeconds?: number): void
  abstract pause(): void
  abstract resume(): void
  abstract stop(): void

  // 公共方法 - 格式化时间
  formatTime(seconds: number) {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`
  }

  // 公共方法 - 保存播放进度
  async savePlaybackProgress(mediaId: number, progressSeconds: number) {
    try {
      const dto = {
        userId: getCurrentUserId(),
        mediaId,
        progressSeconds: Math.floor(progressSeconds),
      }

      const res = await http.put(
        `${this.API_BASE_URL}/api/v1/playback_history`,
        dto,
        {},
        useAuthHeaders(),
      )

      if (res.code === 200) {
        console.log('播放进度保存成功')
      } else {
        console.error(`保存播放进度失败：${res.msg}`)
      }
    } catch (error) {
      console.error('保存播放进度失败:', error)
    }
  }
}
